#!/usr/bin/env python
"""
系统级安装脚本 - 避免虚拟环境冲突
使用系统Python直接安装和运行
"""
import subprocess
import sys
import os
from pathlib import Path

def run_command(cmd, description):
    """执行命令并显示结果"""
    print(f"\n🔧 {description}...")
    print(f"执行命令: {cmd}")
    
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, encoding='utf-8')
        
        if result.stdout:
            print("输出:", result.stdout)
        
        if result.stderr and result.returncode != 0:
            print("错误:", result.stderr)
            return False
        
        print(f"✅ {description} 完成")
        return True
    except Exception as e:
        print(f"❌ {description} 失败: {e}")
        return False

def main():
    print("🚀 Django APScheduler 系统级安装")
    print("=" * 50)
    
    # 获取Python路径
    python_exe = sys.executable
    print(f"使用Python: {python_exe}")
    
    # 进入项目目录
    project_dir = Path(__file__).parent
    os.chdir(project_dir)
    print(f"项目目录: {project_dir}")
    
    # 步骤1：安装依赖
    packages = [
        "Django==4.2.16",
        "apscheduler==3.10.4", 
        "djangorestframework==3.14.0",
        "sqlalchemy==2.0.23"
    ]
    
    for package in packages:
        if not run_command(f'"{python_exe}" -m pip install {package}', f"安装 {package}"):
            print(f"❌ 安装失败，请手动执行: pip install {package}")
    
    # 步骤2：设置Django
    print("\n" + "=" * 50)
    print("🔧 设置Django项目")
    print("=" * 50)
    
    # 设置环境变量
    os.environ['DJANGO_SETTINGS_MODULE'] = 'django_scheduler.settings'
    
    # 创建迁移
    run_command(f'"{python_exe}" manage.py makemigrations', "创建迁移文件")
    run_command(f'"{python_exe}" manage.py makemigrations app', "创建app迁移")
    run_command(f'"{python_exe}" manage.py migrate', "执行数据库迁移")
    
    # 创建超级用户
    print("\n🔧 创建超级用户...")
    create_user_script = '''
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_scheduler.settings")
import django
django.setup()
from django.contrib.auth.models import User
if not User.objects.filter(username="admin").exists():
    User.objects.create_superuser("admin", "admin@example.com", "admin123")
    print("✅ 超级用户创建成功: admin/admin123")
else:
    print("✅ 超级用户已存在")
'''
    
    with open('create_user.py', 'w', encoding='utf-8') as f:
        f.write(create_user_script)
    
    run_command(f'"{python_exe}" create_user.py', "创建超级用户")
    os.remove('create_user.py')
    
    # 创建示例任务
    print("\n🔧 创建示例任务...")
    create_task_script = '''
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_scheduler.settings")
import django
django.setup()
from utils.task_service import TaskService
from app.models import ScheduledTask

if not ScheduledTask.objects.exists():
    task_service = TaskService()
    task = task_service.create_interval_task(
        name='示例任务 - 每3分钟执行',
        description='演示系统功能的示例任务',
        module_path='example_tasks',
        function_name='simple_task',
        minutes=3,
        is_active=True
    )
    print(f"✅ 创建示例任务: {task.name}")
else:
    print("✅ 示例任务已存在")
'''
    
    with open('create_task.py', 'w', encoding='utf-8') as f:
        f.write(create_task_script)
    
    run_command(f'"{python_exe}" create_task.py', "创建示例任务")
    os.remove('create_task.py')
    
    # 完成信息
    print("\n" + "=" * 60)
    print("🎉 安装完成！")
    print("=" * 60)
    
    print(f"\n📋 启动命令 (复制执行):")
    print(f'"{python_exe}" manage.py runserver 8005')
    
    print(f"\n🌐 访问地址:")
    print("• 管理界面: http://127.0.0.1:8005/admin")
    print("• 用户名: admin")
    print("• 密码: admin123")
    print("• API接口: http://127.0.0.1:8005/api")
    
    print(f"\n🔧 调度器管理命令:")
    print(f'"{python_exe}" manage.py start_scheduler')
    print(f'"{python_exe}" manage.py scheduler_status')
    
    # 询问是否立即启动
    print(f"\n❓ 是否立即启动Django服务器？(y/n): ", end="")
    try:
        choice = input().lower().strip()
        if choice in ['y', 'yes', '是', '']:
            print(f"\n🌐 启动Django服务器...")
            os.system(f'"{python_exe}" manage.py runserver 8005')
    except KeyboardInterrupt:
        print("\n👋 退出安装脚本")

if __name__ == '__main__':
    main()